package com.hrm.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hrm.common.R2;
import com.hrm.javabean.DocumentInf;
import com.hrm.javabean.UserInf;
import com.hrm.service.DocumentInfService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/document")
public class DocumentController {
    @Value("${hrm.path}")
    private String basePath;
    @Autowired
    DocumentInfService documentInfService;

    // 浏览器请求预览文件，传入用户id，文件名.后缀
    @GetMapping("/getfile")
    public void getfile(HttpServletResponse response, String userId, String path) {
        String p = path;
        // 有用户id，路径拼接上用户id
        if (userId != null) {
            p = userId + "/" + path;
        }
        System.out.println("路径：" + basePath + p);
        try {
            // 获取后缀
            String str = path.substring(path.lastIndexOf("."));
            System.out.println("后缀：" + str);
            path = new String(path.getBytes(), "iso8859-1");
            if (str.equals(".pdf")) {
                response.setContentType("application/pdf");
                response.addHeader("content-disposition", "inline;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".txt")) {
                response.setContentType("text/plain");
                response.addHeader("content-disposition", "inline;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".ppt") || str.equals(".doc") || str.equals(".xls")) {
                // .ppt/.xls/.doc支持预览文件
                response.setContentType("text/html");
                response.addHeader("content-disposition", "inline;filename=" + path.substring(path.indexOf(".") + 1));
                p = p.substring(0, p.lastIndexOf(".")) + ".html";
            } else {
                response.setContentType("image/jpeg");
                response.addHeader("content-disposition", "inline;filename=" + path.substring(path.indexOf(".") + 1));
            }
            // 输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + p));
            // 输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);


            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
            // 关闭资源
            bos.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 浏览器请求下载文件
    @GetMapping("/download")
    public void download(HttpServletResponse response, String userId, String path) {
        String p = path;
        if (userId != null) {
            p = userId + "/" + path;
        }
        System.out.println("路径：" + basePath + p);
        try {
            // 输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + p));
            // 输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            // 获取后缀
            String str = path.substring(path.lastIndexOf("."));
            System.out.println("后缀：" + str);
            path = new String(path.getBytes(), "iso8859-1");
            if (str.equals(".pdf")) {
                response.setContentType("application/pdf");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".txt")) {
                response.setContentType("text/plain");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".ppt") || str.equals(".pptx")) {
                response.setContentType("application/x-ppt");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".doc") || str.equals(".docx")) {
                response.setContentType("application/x-xls");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            } else if (str.equals(".xls") || str.equals(".xlsx")) {
                response.setContentType("application/x-xls");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            } else {
                response.setContentType("image/jpeg");
                response.addHeader("content-disposition", "attachment;filename=" + path.substring(path.indexOf(".") + 1));
            }

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                bos.write(bytes, 0, len);

            }
            // 关闭资源
            bos.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 上传文件信息到数据库
    @PostMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response, String code, DocumentInf documentInf) throws IOException, ServletException {
        Map map = new HashMap();
        if (!request.getSession().getAttribute("code2").equals(code)) {
            // 验证码有误
            map.put("code", "1");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        System.out.println(documentInf);
        boolean save = documentInfService.save(documentInf);
        System.out.println(documentInf);
        if (save) {
            map.put("code", "200");
            map.put("documentInf", documentInf);
            response.getWriter().write(JSON.toJSONString(map));
        }
    }

    // 获取所有用户上传的文件列表
    // 分页查询
    @GetMapping("/page")
    public void page(HttpServletResponse response, int page, int limit, String fileName, String fileType, String userId) throws IOException {
        log.info("page = {},limit = {},fileName = {},fileType={},userId={}", page, limit, fileName, fileType, userId);
        // 分页构造器
        Page pageInfo = new Page(page, limit);
        // 条件构造
        LambdaQueryWrapper<DocumentInf> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(fileName), DocumentInf::getFileName, ".%" + fileName);
        queryWrapper.like(StringUtils.isNotEmpty(fileType), DocumentInf::getFileType, fileType);
        queryWrapper.eq(StringUtils.isNotEmpty(userId) && Long.valueOf(userId) >= 0, DocumentInf::getUserId, userId);
        // 排序
        queryWrapper.orderByDesc(DocumentInf::getCreateDate);
        // 执行查询
        documentInfService.page(pageInfo, queryWrapper);
        Map map = new HashMap<>();
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getRecords());
        map.put("code", 0);
        response.getWriter().write(JSON.toJSONString(map));
    }

    // 根据文件id删除文件
    @GetMapping("/delete")
    public void delete(HttpServletResponse response, Long id, String flag) throws IOException {
        System.out.println("delete fileId:" + id);
        // 若flag=1表示用户点击删除，删数据库文件信息，还要删磁盘文件，以及生成的预览文件
        if (flag.equals("1")) {
            DocumentInf documentInf = documentInfService.getById(id);
            String s1 = "";
            String s2 = "";
            String s3 = "";

            if (documentInf.getUserId() != null) {
                s1 = basePath + documentInf.getUserId() + "/" + documentInf.getFileName() + documentInf.getFileType();
                s2 = basePath + documentInf.getUserId() + "/" + documentInf.getFileName() + ".html";
                s3 = basePath + documentInf.getUserId() + "/" + documentInf.getFileName();
            } else {
                s1 = basePath + documentInf.getFileName() + documentInf.getFileType();
                s2 = basePath + documentInf.getFileName() + ".html";
                s3 = basePath + documentInf.getFileName();
            }
            // 删文件
            deleteFile(s1, true);
            // 删预览文件（.html）
            deleteFile(s2, true);
            // 删用于文件预览的文件夹
            deleteFile(s3, true);
        }
        // 删数据库文件信息
        boolean remove = documentInfService.removeById(id);
        if (remove) {
            response.getWriter().write("0");
        } else {
            response.getWriter().write("-1");
        }
    }

    // 删除文件或递归删除文件夹
    private void deleteFile(String fileName, boolean isForceDelete) {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        if (file.exists()) {
            if (!isForceDelete) {
                return;
            }
            String[] paths = file.list();
            for (String str : paths) {
                deleteFile(fileName + "\\" + str, isForceDelete);
            }
            file.delete();
            paths = null;
        }
        file = null;
    }
}
